package com.jzr.bedside.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jzr.bedside.db1.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Will run when user login username and pass word validate successfully.
 * There will generate a token return to response.
 */
@Service("authenticationSuccessHandler")
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private TUserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response
            , Authentication authentication) throws IOException {
        UserDetails userDetails = (UserDetails)authentication.getPrincipal();
        logger.info("User: " + userDetails.getUsername() + " Login successfully.");
        this.returnJson(response,authentication,userDetails.getUsername());
    }

    private void returnJson(HttpServletResponse response,Authentication authentication, String userCode) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("status",200);
        map.put("message","ok");
        map.put("msg","ok");
        map.put("tokenType","Bearer");
        map.put("data",tokenProvider.createJwtToken(authentication));
        map.put("userInfo",userService.getUserInfoVo(userCode));

        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().println(objectMapper.writeValueAsString(map));
    }
}
